import styles from './index.less';
import { Component } from 'react';
import withRouter from 'umi/withRouter';
import router from 'umi/router'
class BasicLayout extends Component {
  componentDidMount() {
    let _this = this
    let plusReady = function(callback) {
      if (window.plus) {
        callback();
      } else {
        document.addEventListener('plusready', callback);
      }
    };

    plusReady(function() {
      let firstBack = 0;
      let handleBack = function() {
        let currentWebview = plus.webview.currentWebview();
        let topWebview = plus.webview.getTopWebview();
        let now =
          Date.now ||
          function() {
            return new Date().getTime();
          };

        currentWebview.canBack(function(evt) {
          /**
           * 有可后退的历史记录，则后退。
           * 否则，关闭当前窗口。
           * 如果当前窗口是入口页，那么执行退出的逻辑。
           */
          if(_this.props.location.pathname === '/'){
            if (!firstBack) {
              firstBack = now();
              plus.nativeUI.toast('再按一次退出应用');

              setTimeout(function() {
                firstBack = 0;
              }, 2000);
            } else if (now() - firstBack < 2000) {
              plus.runtime.quit();
            }
          }else{
            router.go(-1);
          }
        });
      };

      plus.key && plus.key.addEventListener('backbutton', handleBack);
    });
  }
  render() {
    return <div className={styles.layout}>{this.props.children}</div>;
  }
}

export default withRouter(BasicLayout);
